var QS_CurrencyChart=function(container,callback){
	this.container=container;
	this.profile={
		menuData:[
			{txt:"1 week",val:"1w",showColumn:false,percision:[0,2],lineWidth:2,closable: false},
			{txt:"3 months",val:"3m",closable: false}
		],
		className:"",
		margin:[0],
		showLabel:false,//show in chart
		autoSlideToActiveTab:false,
		isAPI:true,
		showReturn:true,
		showTab:true,
		percision:[0,0],//the first convert 13,123,456.00,the second convert 13123456.00
		chartText:"1 GBP",
		YlabelWidth:55,
		showBack:true,
		preCloseColor:"#ffbb00",
		refreshRT:true,
		showX:false,
		showY:true,
		showCustomLoading:false,
		showComment:true,//show below chart
		showInterTime:true,//show 8:00 ,nor 8:30
		showLabelTime:true,//show AM/PM
		showYPrecent:false,
		showYPlus:false,
		autToDraw:true,
		showColumn:true,
		tickers:[{"ticker":"0P000002RH","color":"#CE0000","PID":""}]
	};
	this.drawConfig={days:5,frep:5};
	this.cacheData=[];//for column
	this.staticValue={
		tabMenuHeight:25,
		border:1
	};
	this.tValidation = new tickerValidation(this.type);
	this.tValidation.needFilterSecurityType = false;
	this.type=1;
	if(!this.profile.autToDraw){
		this.type=34;
		this.tValidation.needSubscribePushData=false;
	}
	this.currentTab={};
	this.commentHeight=0;
	this.margin={widthMargin:0,heightMargin:0};//
	this.callback=callback;
};
QS_CurrencyChart.prototype={
	init:function(id,profile){
		$.extend(this.profile,profile);
		if(!this.profile.showCustomLoading){
			this.showLoading=function(){
				this.loading.show();
			}
			this.hideLoading=function(){
				this.loading.hide();
			}
		}
		this.id=id||new Date().getTime();
		this._getTickersForChart();
		this._genUI();
	},
	onChartDrawEnd:function(data){
		this._clearColumn();
		this._setColumn(data);	
	},
	onChartDrawStart:function(data){
		if(this.currentTab.showPreClose&&data.length==1){
			var symbol=data[0].symbol,presymbol=String.format("{0}_pre",symbol);
			if(data[0].indicators){
				data.push({
					symbol: presymbol,
					price : data[0].indicators["PrevClose"]
				});
			}
			var mutilColor={},ticker= this.profile.tickers[0];
			mutilColor[symbol]={color:{"line":ticker["color"]}};
			mutilColor[presymbol]={color:{"line":this.profile.preCloseColor}};
			this.miniChart.setMutilColor(mutilColor);
		}
	},
	setTabMenu:function(h){
		this.staticValue.tabMenuHeight=h;
	},
	_setComment:function(){
		this.currencyComment.append(String.format('<span class="rtq-currencyLabel-text">{0}</span>',this.profile.chartText));
		this.commentHeight=this.currencyComment.outerHeight();
	},
	_setLabel:function(){
		this.cavasbg.append(
			String.format(
				'<div class="rtq-currentBGlabel"><span class="rtq-currecnylabel">{0}</span></div>',
				this.profile.chartText));
	},
	_setColumn:function(data){
		//cacheData
		if(this.profile.showColumn&&(typeof this.currentTab.showColumn=='undefined'||this.currentTab.showColumn)){
			var columns=this._getMonth(data),l=columns.length;
			for(var i=0;i<l;i++){
				if(!this._whetherDrawColumn(columns[i][0],((i<l-1)?columns[i+1][0]:(this._getChartWidth()-(this.profile.showY?this.profile.YlabelWidth:0))))) {
					this._setOneColumn(columns[i][1],columns[i][0],false);
				}else{
					this._setOneColumn(columns[i][1],columns[i][0],true);
				}
			}
		}
	},
	_whetherDrawColumn:function(start,next){
		return next-start>12;//(this.currentTab.showDay?5:12);
	},
	_clearColumn:function(){
		this.cavasbg.find(".dvideColumn").remove();
	},
	_setOneColumn:function(content,positionX,showComment){
		$(String.format(
			'<div class="rtq-currecnychart-{0}columns dvideColumn  {1}"><em class="rotate qs-currecnychart-mark">{2}</em></div>',
			(this.currentTab.showDay?"time":"month"),(showComment?content:""),(showComment?content:""))).appendTo(this.cavasbg).css({left:positionX});
	},
	_removeLabelTime:function(timeStr){
		//"09:30 AM"->"09:30";
		return $.trim(timeStr).replace(/\s*(PM|AM|a.m.|p.m.)/ig,"");
	},
	_isIntNum:function(timeStr){
		return timeStr.indexOf(":00")>0;
	},
	_getPureIntPart:function(timeStr){
		//"09:30 AM"-> 9
		return parseInt(timeStr.replace(/:\d*\s*\w*/ig,"").replace(/^0*/g,""));
	},
	_getIntPart:function(timeStr){
		//"09:30 AM"->"9AM";
		return timeStr.replace(/^0*/g,"").replace(/:(\d*\s*)/ig,"");
	},
	_convertTF:function(timeStr){
		//"9:30 PM"-> 21
		var pre=/pm/ig.test(timeStr)?12:0,returnValue=this._getPureIntPart(timeStr);
		return returnValue>=12?returnValue:pre+returnValue;
	},
	_processData:function(t){
		var isInt=false,last=24;
		for(var i=t.length-1;i>=0;i--){
			isInt=false;
			if(t[i][1]==null||typeof t[i][1] == "number"||typeof t[i][1]=='undefined'){
				t.splice(i,1);
				continue;
			}
			if(this._isIntNum(t[i][1])) {//is inter time
				isInt=true;
			}
			if(this.profile.showInterTime&&!isInt){//remove un inter time
				t.splice(i,1);
			}else{
				if(this.currentTab.showInterTime){
					t[i][1]=this._getIntPart(t[i][1]);
				}
				if(this.currentTab.showLowerTime){
					t[i][1]=t[i][1].toLowerCase();
				}
				t[i][2]=isInt;
				t[i][3]=this._convertTF(t[i][1]);
				if(last-t[i][3]>0){
					if(!this.profile.showLabelTime){
						t[i][1]=this._removeLabelTime(t[i][1]);
					}
					last=t[i][3];
				}else{
					t.splice(i,1);
				}
			}
        }
	},
	_concat:function(arr){
		var returnValue=[];
		for(var i=0,l=arr.length;i<l;i++){
			returnValue[i]=[].concat(arr[i]);
		}
		return returnValue;
	},
	_getMonth:function(data,bool){
		var t = [];
		if(this.cacheXAxis.length>0){
			t=this._concat(this.cacheXAxis);
		}else{
			if(data.length>0&&data[0].price){
				t=this._concat(data[0].price.xAxis);
				this.cacheXAxis=this._concat(t);//for changeoutsize redraw columns
			}else{
				return [];
			}
		}
		if(this.currentTab.showDay){
			this._processData(t);
			if(t.length>0){
				var columnData=[],pre=t[0][3],rang=this.currentTab.spacehour|2,temprange=0;
				t[0][0]=this.miniChart.getXorYPosition(t[0][0],bool);
				for(var i=1,l=t.length;i<l;i++){
					columnData=t[i];
					temprange = columnData[3]-pre;
					if(temprange>=rang){
						pre=columnData[3];
					}else{
						columnData[1]="";//column text
					}
		        	t[i][0]=this.miniChart.getXorYPosition(columnData[0],bool);
		        }
		    }
		    if(t.length>12){//too much columns will effect UI
		    	for(var j=t.length-1;j>=0;j--){
		    		if(t[j][3]>18||t[j][3]<9){
		    			t.splice(j,1);
		    		}
		    	}
		    }
		}else{
	        var position=0;
	        for(var pointindex=0,pointlen=t.length;pointindex<pointlen;pointindex++){
	        	position=t[pointindex][0];
	        	t[pointindex][0]=this.miniChart.getXorYPosition(position,bool);
	        }
    	}
        return t;
	},
	_drawChart:function(){
		var self = this,gkey=null;
        if(typeof this.showLoading =='function'){
			this.showLoading();
		}
        this.tValidation.checkTickers(this.cacheTickers, function(o){
            self.miniChart.subscribe(o, self.id,self._getDataProfile(),function(data){
            	self.cacheXAxis=[];
                self.onChartDrawEnd(data);
                if(typeof self.hideLoading=='function'){
					self.hideLoading();
				}
            },function(data){self.onChartDrawStart(data);});
        });
	},
	_setMargin:function(){
		var strMargin= "",len=this.profile.margin.length,margin=0;
		if(len>1){
			for(var i=0,l=len;i<l;i++){
				margin = this.profile.margin[i];
				this.margin[i&1==1?"widthMargin":"heightMargin"]+=margin;
				strMargin+= margin+"px ";
			}
		}else{
			margin = this.profile.margin[0];
			this.margin["widthMargin"]+=margin*2;
			this.margin["heightMargin"]+=margin*2;
			strMargin = margin+"px";
		}
		this.el.css({margin:strMargin});
	},
	_getDataProfile:function(){
		var dataProfile=$.extend(true,{},this.drawConfig);
		if(this.currentTab.showPreClose){
			dataProfile["showPreClose"]=this.currentTab.showPreClose;
		}
		return dataProfile;
	},
	_intiChart:function(){
		this.miniChart = new minichart(this.minChartWrap,this._getChartProfile());
	},
	_getChartProfile:function(){
		var chartProfile={
			lineType: "line",
			showX: this.profile.showX,
			align: "left",
			showYScale: false,
			showY: this.profile.showY,
			percision:this.profile.percision,
			showYPlus:this.profile.showYPlus,
			showYPrecent:this.profile.showYPrecent,
			showYScaleNumber:this.profile.showY,
			width: this._getChartWidth(),
			height: this._getChartHeight(),
			mutilColor: {}
		},ticker=null;
		if(this.profile.showY){
			chartProfile["customLabel"]= true;
			chartProfile["width"]-=this.profile.YlabelWidth;
			chartProfile["marginTop"] = this.profile.showTab?this.staticValue.tabMenuHeight:0;
			chartProfile["customYLabelContainer"]=this.minchartYLabel;
		}
		var tickers=this.profile.tickers.length;
		if(tickers>1){//mutil-chart
			for(var i=0,l=this.profile.tickers.length;i<l;i++){
				ticker= this.profile.tickers[i];
				chartProfile.mutilColor[ticker["PID"]]={color:{"line":ticker["color"]}};//by pid dvide the data
			}
		}else{//single-chart
			chartProfile["color"]={"line":this.profile.tickers[0]["color"]};
		}
		return chartProfile;
	},
	_getTickersForChart:function(){
		var tickerInfo={},tickers=[];
		for(var i=0,l=this.profile.tickers.length;i<l;i++){
			tickerInfo=this.profile.tickers[i];
			tickers.push(tickerInfo.ticker);
		}
		this.cacheTickers=tickers;
	},
	_getChartHeight:function(){
		return ((this.profile.height||this.profile.tempH)-this.margin["heightMargin"]-2*this.staticValue.border-(this.profile.showTab?this.staticValue.tabMenuHeight:0)-this.commentHeight);
	},
	_getChartWidth:function(){
		return ((this.profile.width||this.profile.tempW)-this.margin["widthMargin"]-2*this.staticValue.border);
	},
	_genUI:function(){
		this.el=$('<div class="rtq-currencychart '+this.profile.className+'">'+
			'<div class="rtq-currencytab"></div>'+
			'<div class="rtq-cavnasbg"></div>'+
			'<div class="rtq-currencyminchart-Ylabel"></div>'+
			'<div class="rtq-currencyminchart"></div>'+
			'<div class="rtq-currencycomment"></div></div>').appendTo(this.container);
		this.tabWrap=this.el.find(".rtq-currencytab");
		this.cavasbg=this.el.find(".rtq-cavnasbg");
		this.currencyComment=this.el.find(".rtq-currencycomment");
		if(!this.profile.showCustomLoading){
			this.loading = $('<div class="rtq-currencychart-loading"><img src="../theme/lloyds/loading.gif"></div>').appendTo(this.el);
		}
		this.minchartYLabel=this.el.find(".rtq-currencyminchart-Ylabel");
		this.minChartWrap=this.el.find(".rtq-currencyminchart");
		this._setMargin();
		if(this.profile.showComment){//show below chart
			this._setComment();
		}else{
			this.currencyComment.hide();
		}
		var chartH=this._getChartHeight(), ylabelW=this.profile.showY?this.profile.YlabelWidth:0,chartW=this._getChartWidth();
		if(!this.profile.showY){
			this.minchartYLabel.hide();
		}else{//YLabel 's border is ipx
			this.minchartYLabel.css({width:ylabelW,height:chartH+2});
		}
		//set margin and padding
		if(this.profile.showBack){
			this.cavasbg.css({height:chartH+2,left:ylabelW});
		}
		if(this.profile.showTab){
			this.tabWrap.css({"paddingLeft":ylabelW});
		}
		if(this.profile.showComment){
			this.currencyComment.css({"marginLeft":ylabelW,width:(chartW-ylabelW)});
		}
		if(!this.profile.showCustomLoading){
			this.loading.css({"paddingLeft":ylabelW/4});
		}

		this._intiChart();
		if(this.profile.showLabel){//show in chart
			this._setLabel();
		}
		if(!this.profile.showTab){
			this.tabWrap.hide();
			this.onActiveTab(this.profile.menuData[0]);//default 0
		}else{
			this._genTabMenu();
		}
		if(!this.profile.showBack){
			this.cavasbg.hide();
		}
		this.el.css({
			width:(this.profile.width||this.profile.tempW) - this.margin["widthMargin"]
		});
	},
	_genTabMenu:function(){
		var self = this;
        var cb = {
            onActive: function(tab){
                if(self.currentTab.val != tab.val){
                    self.currentTab = tab;
                    self.onActiveTab(tab);
                }
            }
        };
        this.tabMenu = new Util.TabMenu(this.tabWrap, this.profile.menuData, cb, {
            autoResize:true,
			tabsList: false,
            vertical: false,
            autoSlideToActiveTab:this.profile.autoSlideToActiveTab,
			needTitle:true   // show the "..." when the name is too long.
        });
	},
	onActiveTab:function(tab){
		var today = new Date(), todayIdx = RTQ_ChartUtil.toDateIndex(today),tabvalue=tab.val;
		if(tabvalue.length==2){
			this.drawConfig={};
			this.cacheXAxis=[];
			var step=tabvalue.charAt(0),drawConfig={
				endIndex:todayIdx,
				showReturn:this.profile.showReturn
			},lineWidth=tab.lineWidth||1,precious=tab.percision||this.profile.percision;
			switch(tabvalue.charAt(1)){
				case "d":
					this.currentTab.showDay=true;
					$.extend(true,this.drawConfig,{
						days:step,
						frep:tab.frep||15,//default 5m
						startIndex:todayIdx - (step - 1)
					},drawConfig);
					break;
				case "w":
					$.extend(true,this.drawConfig,{
						days:step*5,
						frep:tab.frep||150
						//startIndex:todayIdx - (step*5 - 1)
					},drawConfig);
					break;
				case "m":
					var y = today.getFullYear(), m = today.getMonth();
	                if (m > step - 1) {
	                    m = m - step;
	                }
	                else {
	                    y -= 1;
	                    m = m + 12 - step;
	                }
					$.extend(true,this.drawConfig,{
						frep:tab.frep||"d",
						startIndex:RTQ_ChartUtil.toDateIndex(new Date(y, m, today.getDate()))
					},drawConfig);
					break;
				default:
					break;
			}
			this.miniChart.setLineWidth(lineWidth);
			this.miniChart.setPercision(precious);
		}
		this._drawChart();
	},
	changeOutSize:function(w,h){
		this.profile.tempW=w;
		this.profile.tempH=h;
		var chartW=this._getChartWidth(),chartH=this._getChartHeight(),ylabelW=this.profile.showY?this.profile.YlabelWidth:0;
		if(this.profile.showY){
			this.minchartYLabel.css({height:chartH+2});
		}
		if(this.profile.showBack){
			this.cavasbg.css({height:chartH+2});
		}
		if(this.profile.showComment){
			this.currencyComment.css({width:(chartW-ylabelW)});
		}
		this.el.css({width:w - this.margin["widthMargin"]});
        if (this.miniChart) {
            this.miniChart.changeOutSize(chartW-ylabelW,chartH);
            this.onChartDrawEnd(this.cacheXAxis);
        }
	},
    clear:function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    }
};